﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Message = Vito.Csharp.Wpf.Controls;

namespace SweetWeather
{
    public class AreaManager
    {
        /// <summary>
        /// 添加数据至配置文件
        /// </summary>
        public static void AddAreaConfig()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\AreaConfig.xml"))
                {
                    doc.Load(path + "Data\\AreaConfig.xml");
                    XmlNode fatherNode = doc.SelectSingleNode("Area");
                    //获取所有省市
                    var province = "http://www.weather.com.cn/data/citydata/china.html";
                    string provinceResult = IPManager.GetWebResponseString(province, Encoding.UTF8);
                    provinceResult = provinceResult.TrimStart('{').TrimEnd('}');
                    provinceResult.Split(',').ToList().ForEach(item =>
                    {
                        if (!String.IsNullOrEmpty(item) && item.Split(':').Count() == 2 && !String.IsNullOrEmpty(item.Split(':')[0]) && !String.IsNullOrEmpty(item.Split(':')[1]))
                        {
                            var pID = item.Split(':')[0].Trim('"');
                            var pName = item.Split(':')[1].Trim('"');
                            XmlElement pele = doc.CreateElement("Province");
                            pele.SetAttribute("Name", pName);
                            pele.SetAttribute("ID", pID);
                            fatherNode.AppendChild(pele);
                            //获取所有省下面的市
                            var city = string.Format("http://www.weather.com.cn/data/citydata/district/{0}.html", pID);
                            string cityResult = IPManager.GetWebResponseString(city, Encoding.UTF8);
                            cityResult = cityResult.TrimStart('{').TrimEnd('}');
                            cityResult.Split(',').ToList().ForEach(cityItem =>
                            {
                                if (!String.IsNullOrEmpty(cityItem) && cityItem.Split(':').Count() == 2 && !String.IsNullOrEmpty(cityItem.Split(':')[0]) && !String.IsNullOrEmpty(cityItem.Split(':')[1]))
                                {
                                    var cName = cityItem.Split(':')[1].Trim('"');
                                    var cID = cityItem.Split(':')[0].Trim('"');
                                    XmlElement cele = doc.CreateElement("City");
                                    cele.SetAttribute("Name", cName);
                                    cele.SetAttribute("ID", pID + cID);
                                    pele.AppendChild(cele);

                                    //获取所有市下面区
                                    var area = string.Format("http://www.weather.com.cn/data/citydata/city/{0}.html", pID + cID);
                                    var areaResult = IPManager.GetWebResponseString(area, Encoding.UTF8);
                                    areaResult = areaResult.TrimStart('{').TrimEnd('}');
                                    areaResult.Split(',').ToList().ForEach(areaitem =>
                                    {
                                        if (!String.IsNullOrEmpty(areaitem) && areaitem.Split(':').Count() == 2 && !String.IsNullOrEmpty(areaitem.Split(':')[0]) && !String.IsNullOrEmpty(areaitem.Split(':')[1]))
                                        {
                                            var aName = areaitem.Split(':')[1].Trim('"');
                                            var aID = areaitem.Split(':')[0].Trim('"');
                                            int proId = 0;
                                            int.TryParse(pID, out proId);
                                            string code;
                                            //海南的DID=Code，无语啊，对比地址：
                                            //http://www.weather.com.cn/data/citydata/city/1013101.html
                                            //http://www.weather.com.cn/data/citydata/city/1011101.html
                                            // 湖北荆州的沙市DID=Code
                                            //http://www.weather.com.cn/data/citydata/city/1012008.html
                                            if (pID == "10131" || aName == "沙市")
                                            {
                                                code = aID;
                                            }
                                            else if (proId < 10105)
                                            {
                                                //注意：直辖市所属的区县市代码拼接方式与非直辖市不通
                                                code = String.Format("{0}{1}{2}", pID.ToString(), aID, cID);
                                            }
                                            else
                                            {
                                                code = String.Format("{0}{1}{2}", pID.ToString(), cID, aID);
                                            }
                                            XmlElement aele = doc.CreateElement("Area");
                                            aele.SetAttribute("Name", aName);
                                            aele.SetAttribute("ID", code);
                                            cele.AppendChild(aele);
                                        }
                                    });
                                }
                            });
                        }
                    });
                    doc.Save(path + "Data\\Appconfig.xml");//保存。
                }
                else
                    Message.MessageBox.Show("数据文件不存在，请重新安装", "操作提示");
            }
            catch
            {
                Message.MessageBox.Show("拉取信息失败，出现异常", "操作提示");
            }

        }

        /// <summary>
        /// 获取配置文件中所有省
        /// </summary>
        /// <returns></returns>
        public static List<City> GetProvince()
        {
            List<City> list = new List<City>();
            try
            {
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\AreaConfig.xml"))
                {
                    XElement element = XElement.Load(path + "Data\\AreaConfig.xml");
                    var result = from pro in element.Elements("Province")
                                 select new City { Code = pro.Attribute("ID").Value, Name = pro.Attribute("Name").Value };
                    list = result.ToList();
                }
                else
                {
                    Message.MessageBox.Show("数据文件不存在，请重新安装", "操作提示");
                }
            }
            catch
            {
                Message.MessageBox.Show("拉取信息失败，出现异常", "操作提示");
            }
            return list;
        }

        /// <summary>
        /// 获取配置文件中省下的市
        /// </summary>
        /// <param name="PID"></param>
        /// <returns></returns>
        public static List<City> GetCityByPID(City Province)
        {
            List<City> list = new List<City>();
            try
            {
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\AreaConfig.xml"))
                {
                    XElement element = XElement.Load(path + "Data\\AreaConfig.xml");
                    var result = from res in element.Elements("Province").Elements("City")
                                 where res.Attribute("ID").Value.Contains(Province.Code)
                                 select new City { Code = res.Attribute("ID").Value, Name = res.Attribute("Name").Value, FullName = Province.Name + res.Attribute("Name").Value };
                    list = result.ToList();
                }
                else
                {
                    Message.MessageBox.Show("数据文件不存在，请重新安装", "操作提示");
                }
            }
            catch
            {
                Message.MessageBox.Show("拉取信息失败，出现异常", "操作提示");
            }
            return list;
        }

        /// <summary>
        /// 获取配置文件中市下的区
        /// </summary>
        /// <param name="CID"></param>
        /// <returns></returns>
        public static List<City> GetAreaByCID(City City)
        {
            List<City> list = new List<City>();
            try
            {
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\AreaConfig.xml"))
                {
                    XElement element = XElement.Load(path + "Data\\AreaConfig.xml");
                    (from res in element.Elements("Province").Elements("City")
                     where res.Attribute("ID").Value == City.Code
                     select res).Elements("Area").ToList().ForEach(item =>
                                  {
                                      City area = new City();
                                      area.Name = item.Attribute("Name").Value;
                                      area.Code = item.Attribute("ID").Value;
                                      area.FullName = City.FullName + area.Name;
                                      list.Add(area);
                                  });
                }
                else
                {
                    Message.MessageBox.Show("数据文件不存在，请重新安装", "操作提示");
                }
            }
            catch
            {
                Message.MessageBox.Show("拉取信息失败，出现异常", "操作提示");
            }
            return list;
        }

        /// <summary>
        /// 根据省市区获取城市详细信息
        /// </summary>
        /// <param name="Province"></param>
        /// <param name="CityName"></param>
        /// <returns></returns>
        public static City GetCityInfoByCityName(string Province, string CityName)
        {
            City city = new City();
            try
            {
                var path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(path + "Data\\AreaConfig.xml"))
                {
                    List<City> list = new List<City>();
                    XElement element = XElement.Load(path + "Data\\AreaConfig.xml");
                    (from res in element.Elements("Province")
                     where res.Attribute("Name").Value.Contains(Province)
                     select res).Elements("City").Elements("Area").ToList().ForEach(item =>
                                  {
                                      if (item.Attribute("Name").Value.Contains(CityName))
                                      {
                                          City area = new City();
                                          area.Name = item.Attribute("Name").Value;
                                          area.Code = item.Attribute("ID").Value;
                                          list.Add(area);
                                      }
                                  });
                    if (list.Count > 0) city = list[0];
                }
                else
                {
                    Message.MessageBox.Show("数据文件不存在，请重新安装", "操作提示");
                }
            }
            catch
            {
                Message.MessageBox.Show("拉取信息失败，出现异常", "操作提示");
            }
            return city;
        }
    }
}
